package com.zhangyu.shadow.ec.main.index;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tepth.shadow.ui.recycler.DataConverter;
import com.tepth.shadow.ui.recycler.ItemType;
import com.tepth.shadow.ui.recycler.MultipleField;
import com.tepth.shadow.ui.recycler.MultipleItemEntity;

import java.util.ArrayList;

/**
 * @author zhangyu
 * @date 2017/10/31
 */

public class IndexDataConverter extends DataConverter {
    @Override
    public ArrayList<MultipleItemEntity> convert() {
        final JSONArray jsonArray = JSONArray.parseObject(getJsonData()).getJSONArray("data");
        int size = jsonArray.size();
        for (int i = 0; i < size; i++) {
            final JSONObject object = jsonArray.getJSONObject(i);
            final String imageUrl = object.getString("imageUrl");
            final String text = object.getString("text");
            final int spanSize = object.getInteger("spanSize");
            final int id = object.getInteger("goodsId");
            final JSONArray banners = object.getJSONArray("banners");

            final ArrayList<String> bannerImages = new ArrayList<>();
            int type = 0;
            if (imageUrl == null && text != null) {
                type = ItemType.TEXT;
            } else if (imageUrl != null && text == null) {
                type = ItemType.IMAGE;
            } else if (imageUrl != null) {
                type = ItemType.TEXT_IMAGE;
            } else if (banners != null) {
                type = ItemType.BANNER;
                final int bannerSize = banners.size();
                for (int j = 0; j < bannerSize; j++) {
                    final String banner = banners.getString(j);
                    bannerImages.add(banner);
                }
            }

            MultipleItemEntity multipleItemEntity = MultipleItemEntity.builder()
                    .setField(MultipleField.ITEM_TYPE, type)
                    .setField(MultipleField.SPAN_SIZE, spanSize)
                    .setField(MultipleField.BANNERS, bannerImages)
                    .setField(MultipleField.ID, id)
                    .setField(MultipleField.TEXT, text)
                    .setField(MultipleField.IMAGE_URL, imageUrl)
                    .build();
            mEntities.add(multipleItemEntity);
        }

        return mEntities;
    }
}
